package com.zl.gmadmin.utils;


import com.zl.gmadmin.common.ApiResponse;
import com.zl.gmadmin.common.IStatus;
import com.zl.gmadmin.exception.BaseException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhangliang
 * @version 1.0
 * @date 2021/1/25 15:17
 */
public class ResponseUtil {

    /**
     * 往 response 写出 json
     *
     * @param response 响应
     * @param status   状态
     * @param data     返回数据
     */
    public static  void renderJson(HttpServletResponse response, IStatus status, Object data){
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(500);

            response.getWriter().write(JsonUtil.toJsonStr(ApiResponse.ofStatus(status,data)));
        }catch (IOException e){
            LogUtil.error("Response写出JSON异常，", e);
        }
    }

    /**
     * 往 response 写出 json
     *BaseException exception
     * @param response  响应
     * @param
     */
    public static void renderJson(HttpServletResponse response, BaseException exception) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            // response返回服务器状态只能是系统自带
            response.setStatus(500);

            response.getWriter().write(JsonUtil.toJsonStr(ApiResponse.ofException(exception)));
        } catch (IOException e) {
            LogUtil.error("Response写出JSON异常，", e);
        }
    }
}
